package com.cssw.fyzb.base.web.interceptor;

import com.cssw.fyzb.base.config.JwtConfig;
import com.cssw.fyzb.base.exception.TokenExpiredException;
import com.cssw.fyzb.base.exception.UnauthorizedException;
import com.cssw.fyzb.base.web.context.UserContext;
import com.cssw.fyzb.base.web.domain.LoginUser;
import com.ydn.simplecache.SimpleCache;
import io.jsonwebtoken.ClaimJwtException;
import io.jsonwebtoken.ExpiredJwtException;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Map;

/**
 * @author Feng Chen
 */
@Component
public class TokenInterceptor implements HandlerInterceptor {

    @Autowired
    private JwtConfig jwtConfig;

    @Autowired
    private SimpleCache simpleCache;

    private static final Logger logger = LoggerFactory.getLogger(TokenInterceptor.class);

    /**
     * 在请求处理之前进行调用（Controller方法调用之前）
     * true表示继续流程; false表示流程中断,不会继续调用其他的拦截器或处理器
     *
     * @param request
     * @param response
     * @param handler
     * @return
     * @throws Exception
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String token = request.getHeader(jwtConfig.getHeader());
        if (StringUtils.isEmpty(token)) {
            logger.info(">>>>>token is null:" + request.getServletPath());
            throw new UnauthorizedException();
        }

        String cacheUserId = simpleCache.get("FY_TOKEN_" + token);
        if (null == cacheUserId || "".equals(cacheUserId)){
            logger.info(">>>>>cacheUserId is null:" + request.getServletPath());
            throw new UnauthorizedException();
        }

        //单点登录判断
        String cacheToken = simpleCache.get("FY_TOKEN_" + cacheUserId);
        if (!token.equals(cacheToken)) {
            logger.info("token expire: " + token + ">>" + cacheToken);
            throw new TokenExpiredException();
        }

        UserContext.set(LoginUser.newUser(cacheUserId));
        return true;
    }

    /**
     * 请求处理之后进行调用（Controller方法调用之后）
     *
     * @param request
     * @param response
     * @param handler
     * @param modelAndView
     * @throws Exception
     */
    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {

    }

    /**
     * 在整个请求结束之后被调用（主要是用于进行资源清理工作）
     *
     * @param request
     * @param response
     * @param handler
     * @param ex
     * @throws Exception
     */
    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        UserContext.remove();
    }
}
